<template>
  <div class="booking-form">
    <el-form :model="form" label-width="100px">
      <!-- 日期时间选择 -->
      <el-form-item label="预约时间" prop="start_time">
        <el-date-picker
            v-model="form.start_time"
            type="datetime"
            :disabled-date="disabledDate"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        placeholder="选择预约时间"
        />
      </el-form-item>

      <el-form-item label="车型选择" prop="type_id">
        <el-select v-model="form.type_id" placeholder="请选择车型" @change="calculateDistance">
          <el-option
              v-for="type in teamTypes"
              :key="type.id"
              :label="type.team_type_name"
              :value="type.id"
          />
        </el-select>
      </el-form-item>

      <!-- 地址选择 -->
      <el-form-item label="搬出地址">
        <el-input
            v-model="form.fromAddress"
            placeholder="点击选择搬出地址"
            readonly
            @click="openMapDialog('from')"
        >
          <template #suffix>
            <el-icon><Location /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="搬入地址">
        <el-input
            v-model="form.toAddress"
            placeholder="点击选择搬入地址"
            readonly
            @click="openMapDialog('to')"
        >
          <template #suffix>
            <el-icon><Location /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="起点楼层">
        <el-input-number v-model="form.start_floor" :min="1" @change="calculateDistance"/>
      </el-form-item>

      <el-form-item label="终点楼层">
        <el-input-number v-model="form.end_floor" :min="1" @change="calculateDistance"/>
      </el-form-item>

      <el-form-item label="是否有电梯">
        <el-switch v-model="form.has_elevator" @change="calculateDistance"/>
      </el-form-item>

      <el-form-item label="打包服务" v-if="false">
        <el-radio-group v-model="form.is_help">
          <el-radio :label="0">需要</el-radio>
          <el-radio :label="1">不需要</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 距离显示 -->
      <el-form-item label="预估距离" v-if="distance">
        <span>{{ distance }} 公里</span>
      </el-form-item>

      <el-form-item label="费用明细" v-if="priceDetail.totalPrice > 0">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="基础费用">¥{{ priceDetail.baseFee }}</el-descriptions-item>
          <el-descriptions-item label="距离费用">¥{{ priceDetail.distanceFee }}</el-descriptions-item>
          <el-descriptions-item label="楼层费用">¥{{ priceDetail.floorPrice }}</el-descriptions-item>
          <el-descriptions-item label="总价费用">¥{{ priceDetail.totalPrice }}</el-descriptions-item>
        </el-descriptions>
      </el-form-item>

      <!-- 表单按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handlePayment">立即支付</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 地图弹窗 -->
    <el-dialog
        v-model="mapVisible"
        :title="mapType === 'from' ? '选择搬出地址' : '选择搬入地址'"
        width="80%"
        :destroy-on-close="false"
        @close="handleDialogClose"
    >
      <div class="map-container">
        <div class="search-box">
          <el-input
              id="searchInput"
              v-model="searchKeyword"
              placeholder="搜索地址"
              @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <div id="mapContainer" class="map"></div>
      </div>
      <template #footer>
        <el-button @click="mapVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmLocation">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, onBeforeUnmount,nextTick} from 'vue'
import {ElMessage} from 'element-plus'
import {Location, Search} from '@element-plus/icons-vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import {useRoute} from "vue-router";
import {get, payPost, post} from "@/net/index.js";
import router from "@/router/index.js";

// 表单数据
const route = useRoute()
const userInfo=ref()
const form = reactive({
  team_id: route.params.id, // 从路由获取团队ID
  type_id: '', // 车型ID
  start_time: '', // 合并date和time
  start_location: '', // 原fromAddress
  end_location: '', // 原toAddress
  fromLocation: null, // 地图位置对象
  toLocation: null, // 地图位置对象
  start_floor: 1, // 起点楼层
  end_floor: 1, // 终点楼层
  has_elevator: true, // 是否有电梯
  money: '', // 预估费用
  status: 0, // 订单状态
  is_help: 0 // 是否需要打包服务
})

const priceDetail = reactive({
  totalPrice: 0,
  baseFee: 0,
  distanceFee: 0,
  floorPrice: 0
})

// 添加价格规则的ref
const priceRules = ref([])

//支付相关
const payDialogVisible = ref(false)


// 处理支付按钮点击
const handlePayment = async () => {
  if (!form.start_time) {
    ElMessage.warning('请选择预约时间')
    return
  }
  if (!form.type_id) {
    ElMessage.warning('请选择车型')
    return
  }
  if (!form.fromAddress || !form.toAddress) {
    ElMessage.warning('请选择地址')
    return
  }
  if (!form.money) {
    ElMessage.warning('请等待费用计算')
    return
  }
  // 直接调用支付函数
  confirmPayment()
}

//支付
const confirmPayment = () => {
  const formatDateTime = (date) => {
    if (!date) return null;
    return new Date(date).toISOString().replace('T', ' ').split('.')[0];
  };

  userInfo.value = JSON.parse(window.localStorage.getItem('user'))

  const orderData = {
    team_id: form.team_id,
    type_id: form.type_id,
    start_location: form.fromAddress,
    end_location: form.toAddress,
    start_time: formatDateTime(form.start_time),
    is_help: form.is_help,
    money: priceDetail.totalPrice.toString(),
    status: 0,
    create_time: formatDateTime(new Date()),
    user_id: userInfo.value.id,
  }

  payPost('/api/pay/create', orderData,
      (htmlForm) => {
        // 创建一个隐藏的容器
        const container = document.createElement('div')
        container.style.display = 'none'
        container.innerHTML = htmlForm
        document.body.appendChild(container)

        // 获取支付宝表单
        const payForm = container.querySelector('form')
        if (payForm) {
          payForm.submit()
          document.body.removeChild(container)
        } else {
          ElMessage.error('支付表单创建失败')
        }
      },
      (error) => {
        console.error('支付请求失败:', error)
        ElMessage.error('支付系统异常，请重试')
      }
  )
}

const teamTypes = ref([])


// 地图相关
const mapVisible = ref(false)
const mapType = ref('from')
const map = ref(null)
const marker = ref(null)
const mapLoaded = ref(false)
const searchKeyword = ref('')
const distance = ref(null)
const selectedLocation = ref(null)

// 获取车型列表
const getTeamTypes = () => {
  get(`/api/teamType/getAllTeamTypeList`,(res)=>{

    teamTypes.value = res
    // console.log(teamList.value)
  },(err)=>{
    ElMessage.warning("请求失败")
    console.log(err)
  })
}

// 添加加载价格规则的方法
const loadPriceRules = () => {
  get(`/api/priceRule/getAllPriceRuleList`, (res) => {
    priceRules.value = res
  }, (err) => {
    ElMessage.warning("获取价格规则失败")
    console.log(err)
  })
}

// 初始化地图
const initMap = async () => {
  try {
    if (!window.AMap) {
      window._AMapSecurityConfig = {
        securityJsCode: '049ff360565a94416c37198c0769490b'
      }
      await AMapLoader.load({
        key: 'eca118686be41f08b3cdee78f884b7d2',
        version: '2.0',
        plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.Geocoder', 'AMap.AutoComplete', 'AMap.PlaceSearch','AMap.Geolocation']
      })
    }
    // 确保地图容器存在
    await nextTick()
    map.value = new AMap.Map('mapContainer', {
      zoom: 13,
      center: [116.397428, 39.90923]
    })

    // 创建标记点
    marker.value = new AMap.Marker({
      map: map.value,
      draggable: true
    })
    // 创建 Geocoder 实例
    const geocoder = new AMap.Geocoder()
    // 地图点击事件
    map.value.on('click', (e) => {
      const lnglat = e.lnglat
      marker.value.setPosition(lnglat)

      geocoder.getAddress([lnglat.getLng(), lnglat.getLat()], (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          selectedLocation.value = {
            address: result.regeocode.formattedAddress,
            lnglat: lnglat
          }
          searchKeyword.value = result.regeocode.formattedAddress
        }
      })
    })

    // 标记点拖动结束事件
    marker.value.on('dragend', (e) => {
      const lnglat = marker.value.getPosition()
      geocoder.getAddress([lnglat.getLng(), lnglat.getLat()], (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          selectedLocation.value = {
            address: result.regeocode.formattedAddress,
            lnglat: lnglat
          }
          searchKeyword.value = result.regeocode.formattedAddress
        }
      })
    })

    map.value.addControl(new AMap.ToolBar())
    map.value.addControl(new AMap.Scale())

    mapLoaded.value = true
  } catch (error) {
    console.error('地图初始化失败:', error)
    ElMessage.error('地图加载失败，请刷新重试')
  }
}


// 添加获取当前位置的函数
const getCurrentLocation = () => {
  return new Promise((resolve, reject) => {
    const geolocation = new AMap.Geolocation({
      enableHighAccuracy: true, //启用高精度定位
      timeout: 10000, //超时时间10秒
      buttonPosition: 'RB',//定位按钮在右下角
      buttonOffset: new AMap.Pixel(10, 20),//按钮偏移量
      zoomToAccuracy: true //定位成功后自动调整地图层级
    })

    map.value.addControl(geolocation)

    geolocation.getCurrentPosition((status, result) => {
      if (status === 'complete') {
        resolve(result)
      } else {
        reject(result)
      }
    })
  })
}
// 处理地址搜索
const handleSearch = (value) => {
  if (!value) return

  const placeSearch = new AMap.PlaceSearch({
    map: map.value
  })

  placeSearch.search(value, (status, result) => {
    if (status === 'complete' && result.info === 'OK') {
      const poi = result.poiList.pois[0]
      const lnglat = new AMap.LngLat(poi.location.lng, poi.location.lat)
      marker.value.setPosition(lnglat)
      map.value.setCenter(lnglat)

      selectedLocation.value = {
        address: poi.name,
        lnglat: lnglat
      }
    }
  })
}

// 打开地图弹窗的函数修改
const openMapDialog = async (type) => {
  mapType.value = type
  mapVisible.value = true
  searchKeyword.value = ''
  selectedLocation.value = null

  await nextTick()

  if (!mapLoaded.value) {
    await initMap()
  }

  // 如果是搬入地址且没有已选位置，则获取当前位置
  if (type === 'to' && !form.toLocation) {
    try {
      const result = await getCurrentLocation()
      const lnglat = new AMap.LngLat(result.position.lng, result.position.lat)
      marker.value.setPosition(lnglat)
      map.value.setCenter(lnglat)

      // 获取地址信息
      const geocoder = new AMap.Geocoder()
      geocoder.getAddress([lnglat.getLng(), lnglat.getLat()], (status, addressResult) => {
        if (status === 'complete' && addressResult.info === 'OK') {
          selectedLocation.value = {
            address: addressResult.regeocode.formattedAddress,
            lnglat: lnglat
          }
          searchKeyword.value = addressResult.regeocode.formattedAddress
        }
      })
    } catch (error) {
      console.error('获取当前位置失败:', error)
      ElMessage.warning('无法获取当前位置，请手动选择地址')
    }
  } else {
    // 原有的逻辑保持不变
    if (mapType.value === 'from' && form.fromLocation) {
      marker.value.setPosition(form.fromLocation)
      map.value.setCenter(form.fromLocation)
      searchKeyword.value = form.fromAddress
    } else if (mapType.value === 'to' && form.toLocation) {
      marker.value.setPosition(form.toLocation)
      map.value.setCenter(form.toLocation)
      searchKeyword.value = form.toAddress
    } else {
      marker.value.setPosition(map.value.getCenter())
    }
  }
}
const handleDialogClose = () => {
  // 不销毁地图，只隐藏对话框
  mapVisible.value = false
}
// 确认选择的地址
const confirmLocation = () => {
  if (!selectedLocation.value) {
    ElMessage.warning('请选择地址')
    return
  }

  if (mapType.value === 'from') {
    form.fromAddress = selectedLocation.value.address
    form.fromLocation = selectedLocation.value.lnglat
  } else {
    form.toAddress = selectedLocation.value.address
    form.toLocation = selectedLocation.value.lnglat
  }

  calculateDistance()
  mapVisible.value = false
}

//距离计算
const calculateDistance = () => {
  if (form.fromLocation && form.toLocation) {
    const from = form.fromLocation
    const to = form.toLocation
    distance.value = (from.distance(to) / 1000).toFixed(1)
    calculatePrice() // 计算完距离后立即计算价格
  }
}

// 计算价格
const calculatePrice = () => {
  if (!form.type_id || !distance.value) return

  const selectedType = teamTypes.value.find(type => type.id === form.type_id)
  if (!selectedType) return

  // 基础费用
  priceDetail.baseFee = Number(selectedType.team_type_money)

  // 获取每公里费用规则
  const distanceRule = priceRules.value.find(rule => rule.ruleName === '每公里费用')
  // 距离费用
  priceDetail.distanceFee = distance.value * (distanceRule ? Number(distanceRule.price) : 0)

  // 获取楼层费用规则
  const floorRule = priceRules.value.find(rule => rule.ruleName === '每层楼费用')
  // 楼层费用
  if (!form.has_elevator && floorRule) {
    const startFloorCharge = Math.max(0, form.start_floor - 1) * Number(floorRule.price)
    const endFloorCharge = Math.max(0, form.end_floor - 1) * Number(floorRule.price)
    priceDetail.floorPrice = startFloorCharge + endFloorCharge
  } else {
    priceDetail.floorPrice = 0
  }

  // 计算总价
  priceDetail.totalPrice = priceDetail.baseFee + priceDetail.distanceFee + priceDetail.floorPrice
  form.money = priceDetail.totalPrice.toString()
}

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}


// 重置表单
const resetForm = () => {
  Object.assign(form, {
    type_id: '',
    start_time: '',
    fromAddress: '',
    toAddress: '',
    fromLocation: null,
    toLocation: null,
    start_floor: 1,
    end_floor: 1,
    has_elevator: true,
    money: '',
    is_help: 0
  })
  distance.value = null
  Object.assign(priceDetail, {
    totalPrice: 0,
    baseFee: 0,
    distanceFee: 0,
    floorPrice: 0
  })
}

// 组件销毁时清理地图
onBeforeUnmount(() => {
  if (map.value) {
    map.value.destroy()
    map.value = null
  }
})

//刷新页面加载
onMounted(()=>{
  getTeamTypes()
  loadPriceRules()
})
</script>

<style scoped>
.booking-form {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.map-container {
  position: relative;
  height: 500px;
}

.map {
  width: 100%;
  height: 100%;
}

.search-box {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 300px;
  z-index: 999;
  background: white;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pay-info {
  text-align: center;
  padding: 20px 0;
}
.pay-info p {
  margin: 10px 0;
  font-size: 16px;
}
</style>